//
//  UserAccount.swift
//  01_新浪微博
//
//  Created by 黄蓉 on 15/12/14.
//  Copyright © 2015年 黄蓉. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {

    var access_token: String?
    var expires_in: NSTimeInterval = 0  {
        didSet{
            
         expiresData = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var uid: String?
    var expiresData: NSDate?
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?

    init(dict:[String : AnyObject]) {
//       access_token = dict["access_token"] as! String
//       expires_in = dict["expires_in"] as! Double
//        uid = dict["uid"] as! String
        
        super.init()
        self.setValuesForKeysWithDictionary(dict)
       
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
   
    
    
    static let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! + "/123.plist"
    ///归档
    func  saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
    }
    ///解档
   class func loadAccount() -> UserAccount? {
    if let count = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.filePath) as? UserAccount {
        //判断账号是否过期.
        if count.expiresData!.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            return count
        }
    }
    return nil
}
    
    
    //还可以json的序列化和反序列化进行存储
    //将对象转化为二进制文件存储
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresData, forKey: "expiresData")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //将二进制文件转为对象
     required init?(coder aDecoder: NSCoder) {
       access_token = (aDecoder.decodeObjectForKey("access_token") as? String
        )!
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        name  = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

       uid = aDecoder.decodeObjectForKey("uid") as? String
        expiresData = (aDecoder.decodeObjectForKey("expiresData") as? NSDate)!
       
    }
    
}
